<template>
  <div class="dashboard">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="header-info">
        <h2>工作台</h2>
        <p>欢迎回来，{{ userInfo.nickname || '管理员' }} | {{ currentTime }}</p>
      </div>
      <div class="header-actions">
        <el-button type="primary" icon="el-icon-refresh" @click="refreshData">刷新数据</el-button>
      </div>
    </div>

    <!-- 数据统计卡片 -->
    <div class="stats-cards" v-loading="statsLoading">
      <div class="stat-card" @click="navigateTo('/users')">
        <div class="stat-icon user-icon">
          <el-icon><User /></el-icon>
        </div>
        <div class="stat-info">
          <div class="stat-number">{{ overviewStats.userCount || 0 }}</div>
          <div class="stat-label">注册用户</div>
        </div>
        <div class="stat-trend">
          <el-icon><Top /></el-icon>
          <span>12%</span>
        </div>
      </div>

      <div class="stat-card" @click="navigateTo('/culture')">
        <div class="stat-icon culture-icon">
          <el-icon><Picture /></el-icon>
        </div>
        <div class="stat-info">
          <div class="stat-number">{{ overviewStats.cultureCount || 0 }}</div>
          <div class="stat-label">剪纸文化</div>
        </div>
        <div class="stat-trend">
          <el-icon><Top /></el-icon>
          <span>8%</span>
        </div>
      </div>

      <div class="stat-card" @click="navigateTo('/tutorials')">
        <div class="stat-icon tutorial-icon">
          <el-icon><VideoCamera /></el-icon>
        </div>
        <div class="stat-info">
          <div class="stat-number">{{ overviewStats.tutorialCount || 0 }}</div>
          <div class="stat-label">教学视频</div>
        </div>
        <div class="stat-trend">
          <el-icon><Top /></el-icon>
          <span>15%</span>
        </div>
      </div>

      <div class="stat-card" @click="navigateTo('/news')">
        <div class="stat-icon news-icon">
          <el-icon><Bell /></el-icon>
        </div>
        <div class="stat-info">
          <div class="stat-number">{{ overviewStats.newsCount || 0 }}</div>
          <div class="stat-label">文化活动</div>
        </div>
        <div class="stat-trend">
          <el-icon><Top /></el-icon>
          <span>5%</span>
        </div>
      </div>
    </div>

    <!-- 图表和数据展示 -->
    <el-row :gutter="20" class="charts-row">
      <!-- 用户增长趋势 -->
      <el-col :xs="24" :lg="12">
        <div class="chart-card">
          <div class="card-header">
            <h3>用户增长趋势</h3>
            <el-button-group size="small">
              <el-button :type="userChartPeriod === 'week' ? 'primary' : ''" @click="changeUserChartPeriod('week')">本周</el-button>
              <el-button :type="userChartPeriod === 'month' ? 'primary' : ''" @click="changeUserChartPeriod('month')">本月</el-button>
              <el-button :type="userChartPeriod === 'year' ? 'primary' : ''" @click="changeUserChartPeriod('year')">本年</el-button>
            </el-button-group>
          </div>
          <div ref="userChartRef" class="chart-container"></div>
        </div>
      </el-col>

      <!-- 内容分布 -->
      <el-col :xs="24" :lg="12">
        <div class="chart-card">
          <div class="card-header">
            <h3>内容分布统计</h3>
            <div class="chart-legend">
              <span class="legend-item">
                <span class="legend-dot culture"></span>
                剪纸文化
              </span>
              <span class="legend-item">
                <span class="legend-dot tutorial"></span>
                教学视频
              </span>
              <span class="legend-item">
                <span class="legend-dot news"></span>
                文化活动
              </span>
            </div>
          </div>
          <div ref="contentChartRef" class="chart-container"></div>
        </div>
      </el-col>
    </el-row>

    <!-- 快捷操作和系统信息 -->
    <el-row :gutter="20" class="bottom-row">
      <!-- 快捷操作 -->
      <el-col :xs="24" :lg="12">
        <div class="quick-actions-card">
          <div class="card-header">
            <h3>快捷操作</h3>
          </div>
          <div class="quick-actions">
            <div class="action-item" @click="navigateTo('/users')">
              <div class="action-icon user-bg">
                <el-icon><User /></el-icon>
              </div>
              <div class="action-content">
                <h4>用户管理</h4>
                <p>管理用户信息与权限</p>
              </div>
              <div class="action-arrow">
                <el-icon><ArrowRight /></el-icon>
              </div>
            </div>

            <div class="action-item" @click="navigateTo('/culture')">
              <div class="action-icon culture-bg">
                <el-icon><Picture /></el-icon>
              </div>
              <div class="action-content">
                <h4>剪纸文化</h4>
                <p>管理剪纸文化内容</p>
              </div>
              <div class="action-arrow">
                <el-icon><ArrowRight /></el-icon>
              </div>
            </div>

            <div class="action-item" @click="navigateTo('/tutorials')">
              <div class="action-icon tutorial-bg">
                <el-icon><VideoCamera /></el-icon>
              </div>
              <div class="action-content">
                <h4>教学视频</h4>
                <p>管理教学视频内容</p>
              </div>
              <div class="action-arrow">
                <el-icon><ArrowRight /></el-icon>
              </div>
            </div>

            <div class="action-item" @click="navigateTo('/news')">
              <div class="action-icon news-bg">
                <el-icon><Bell /></el-icon>
              </div>
              <div class="action-content">
                <h4>文化活动</h4>
                <p>管理文化活动资讯</p>
              </div>
              <div class="action-arrow">
                <el-icon><ArrowRight /></el-icon>
              </div>
            </div>

            <div class="action-item" @click="navigateTo('/banners')">
              <div class="action-icon banner-bg">
                <el-icon><PictureRounded /></el-icon>
              </div>
              <div class="action-content">
                <h4>轮播图</h4>
                <p>管理首页轮播图</p>
              </div>
              <div class="action-arrow">
                <el-icon><ArrowRight /></el-icon>
              </div>
            </div>

            <div class="action-item" @click="navigateTo('/settings')">
              <div class="action-icon setting-bg">
                <el-icon><Setting /></el-icon>
              </div>
              <div class="action-content">
                <h4>系统设置</h4>
                <p>配置系统参数</p>
              </div>
              <div class="action-arrow">
                <el-icon><ArrowRight /></el-icon>
              </div>
            </div>
          </div>
        </div>
      </el-col>

      <!-- 系统信息 -->
      <el-col :xs="24" :lg="12">
        <div class="system-info-card">
          <div class="card-header">
            <h3>系统信息</h3>
            <el-tag type="success" size="small">运行正常</el-tag>
          </div>
          <div class="system-info">
            <div class="info-section">
              <h4>平台数据</h4>
              <div class="info-items">
                <div class="info-row">
                  <span class="info-label">注册用户</span>
                  <span class="info-value">{{ overviewStats.userCount || 0 }}</span>
                </div>
                <div class="info-row">
                  <span class="info-label">内容总数</span>
                  <span class="info-value">{{ totalContent }}</span>
                </div>
                <div class="info-row">
                  <span class="info-label">学习记录</span>
                  <span class="info-value">{{ overviewStats.studyCount || 0 }}</span>
                </div>
              </div>
            </div>

            <div class="info-section">
              <h4>内容统计</h4>
              <div class="info-items">
                <div class="info-row">
                  <span class="info-label">剪纸文化</span>
                  <span class="info-value">{{ overviewStats.cultureCount || 0 }} 篇</span>
                </div>
                <div class="info-row">
                  <span class="info-label">教学视频</span>
                  <span class="info-value">{{ overviewStats.tutorialCount || 0 }} 个</span>
                </div>
                <div class="info-row">
                  <span class="info-label">文化活动</span>
                  <span class="info-value">{{ overviewStats.newsCount || 0 }} 场</span>
                </div>
              </div>
            </div>

            <div class="info-section">
              <h4>系统信息</h4>
              <div class="info-items">
                <div class="info-row">
                  <span class="info-label">平台版本</span>
                  <span class="info-value">v1.0.0</span>
                </div>
                <div class="info-row">
                  <span class="info-label">技术架构</span>
                  <span class="info-value">Vue3 + Spring Boot</span>
                </div>
                <div class="info-row">
                  <span class="info-label">最后登录</span>
                  <span class="info-value">{{ formatDateTime(userInfo.lastLoginTime) }}</span>
                </div>
              </div>
            </div>

            <div class="system-actions">
              <el-button type="primary" size="small" @click="navigateTo('/settings')">
                <el-icon><Setting /></el-icon>
                系统设置
              </el-button>
              <el-button type="info" size="small" @click="navigateTo('/logs')">
                <el-icon><Document /></el-icon>
                查看日志
              </el-button>
            </div>
          </div>
        </div>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import { ref, computed, onMounted, onUnmounted, nextTick } from 'vue'
import { ElMessage } from 'element-plus'
import { useRouter } from 'vue-router'
import * as echarts from 'echarts'
import {
  User,
  Picture,
  VideoCamera,
  Bell,
  Top,
  ArrowRight,
  Setting,
  Document,
  PictureRounded
} from '@element-plus/icons-vue'
import {
  getOverviewStats,
  getCultureCategoryStats,
  getUserGrowthTrend
} from '@/api/admin'

export default {
  name: 'Dashboard',
  components: {
    User,
    Picture,
    VideoCamera,
    Bell,
    Top,
    ArrowRight,
    Setting,
    Document,
    PictureRounded
  },
  setup() {
    const router = useRouter()
    const statsLoading = ref(false)
    const overviewStats = ref({})
    const currentTime = ref('')
    const userInfo = ref({})
    const userChartPeriod = ref('week')
    const cultureCategories = ref([])

    // 图表引用
    const userChartRef = ref(null)
    const contentChartRef = ref(null)
    let userChart = null
    let contentChart = null
    let timeInterval = null

    // 计算属性
    const totalContent = computed(() => {
      return (overviewStats.value.cultureCount || 0) +
             (overviewStats.value.tutorialCount || 0) +
             (overviewStats.value.newsCount || 0)
    })

    // 获取用户信息
    const getUserInfo = () => {
      const userInfoStr = localStorage.getItem('userInfo')
      if (userInfoStr) {
        userInfo.value = JSON.parse(userInfoStr)
      }
    }

    // 获取统计数据
    const fetchStats = async () => {
      try {
        statsLoading.value = true

        // 获取总体统计数据
        const overviewResponse = await getOverviewStats()
        if (overviewResponse.code === 200) {
          overviewStats.value = overviewResponse.data || {}
        }

        // 获取文化分类数据
        try {
          const categoryResponse = await getCultureCategoryStats()
          if (categoryResponse.code === 200) {
            cultureCategories.value = categoryResponse.data || []
          }
        } catch (error) {
          console.warn('获取文化分类统计失败:', error)
        }

      } catch (error) {
        console.error('获取统计数据失败:', error)
        ElMessage.warning('获取统计数据失败，显示默认数据')

        // 使用默认数据
        overviewStats.value = {
          userCount: 0,
          cultureCount: 0,
          tutorialCount: 0,
          newsCount: 0,
          studyCount: 0
        }
      } finally {
        statsLoading.value = false
      }
    }

    // 导航到指定页面
    const navigateTo = (path) => {
      router.push(path)
    }

    // 切换用户图表时间周期
    const changeUserChartPeriod = (period) => {
      userChartPeriod.value = period
      updateUserChart()
    }

    // 刷新数据
    const refreshData = async () => {
      ElMessage.info('正在刷新数据...')
      await fetchStats()
      updateCharts()
      ElMessage.success('数据刷新完成')
    }

    // 更新当前时间
    const updateCurrentTime = () => {
      const now = new Date()
      currentTime.value = now.toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit',
        second: '2-digit'
      })
    }

    // 初始化用户增长趋势图
    const initUserChart = () => {
      if (!userChartRef.value) return

      userChart = echarts.init(userChartRef.value)
      updateUserChart()
    }

    // 更新用户图表
    const updateUserChart = async () => {
      if (!userChart) return

      try {
        // 从后端获取真实数据
        const response = await getUserGrowthTrend(userChartPeriod.value)
        
        if (response.code === 200 && response.data) {
          const { labels, data } = response.data
          
          const option = {
            tooltip: {
              trigger: 'axis',
              axisPointer: {
                type: 'shadow'
              },
              formatter: function(params) {
                return `${params[0].name}<br/>新增用户: ${params[0].value}人`
              }
            },
            grid: {
              left: '3%',
              right: '4%',
              bottom: '3%',
              top: '10%',
              containLabel: true
            },
            xAxis: {
              type: 'category',
              data: labels,
              axisLine: {
                lineStyle: {
                  color: '#e6e6e6'
                }
              },
              axisLabel: {
                color: '#666'
              }
            },
            yAxis: {
              type: 'value',
              axisLine: {
                lineStyle: {
                  color: '#e6e6e6'
                }
              },
              axisLabel: {
                color: '#666',
                formatter: '{value}'
              },
              splitLine: {
                lineStyle: {
                  color: '#f0f0f0'
                }
              },
              minInterval: 1
            },
            series: [{
              name: '新增用户',
              data: data,
              type: 'bar',
              barWidth: '50%',
              itemStyle: {
                color: '#8B0000',
                borderRadius: [4, 4, 0, 0]
              }
            }]
          }

          userChart.setOption(option)
        }
      } catch (error) {
        console.error('获取用户增长趋势失败:', error)
        ElMessage.warning('获取用户增长数据失败')
      }
    }

    // 初始化内容分布图
    const initContentChart = () => {
      if (!contentChartRef.value) return

      contentChart = echarts.init(contentChartRef.value)
      updateContentChart()
    }

    // 更新内容分布图
    const updateContentChart = () => {
      if (!contentChart) return

      const cultureCount = overviewStats.value.cultureCount || 0
      const tutorialCount = overviewStats.value.tutorialCount || 0
      const newsCount = overviewStats.value.newsCount || 0

      const option = {
        tooltip: {
          trigger: 'item',
          formatter: '{b}: {c} ({d}%)'
        },
        legend: {
          bottom: '5%',
          left: 'center',
          textStyle: {
            color: '#666'
          }
        },
        series: [{
          name: '内容分布',
          type: 'pie',
          radius: ['40%', '70%'],
          center: ['50%', '45%'],
          avoidLabelOverlap: false,
          label: {
            show: false
          },
          emphasis: {
            label: {
              show: true,
              fontSize: '16',
              fontWeight: 'bold'
            }
          },
          data: [
            {
              value: cultureCount,
              name: '剪纸文化',
              itemStyle: { color: '#8B0000' }
            },
            {
              value: tutorialCount,
              name: '教学视频',
              itemStyle: { color: '#00bcd4' }
            },
            {
              value: newsCount,
              name: '文化活动',
              itemStyle: { color: '#43e97b' }
            }
          ]
        }]
      }

      contentChart.setOption(option)
    }

    // 更新所有图表
    const updateCharts = () => {
      updateUserChart()
      updateContentChart()
    }

    // 时间格式化
    const formatDateTime = (dateTime) => {
      if (!dateTime) return '暂无记录'
      return new Date(dateTime).toLocaleString('zh-CN')
    }

    // 窗口大小改变时重新调整图表
    const handleResize = () => {
      if (userChart) userChart.resize()
      if (contentChart) contentChart.resize()
    }

    // 组件挂载
    onMounted(async () => {
      getUserInfo()
      updateCurrentTime()

      // 设置定时器更新时间
      timeInterval = setInterval(updateCurrentTime, 1000)

      // 获取统计数据
      await fetchStats()

      // 等待DOM更新后初始化图表
      await nextTick()
      initUserChart()
      initContentChart()

      // 添加窗口大小改变监听
      window.addEventListener('resize', handleResize)
    })

    // 组件卸载
    onUnmounted(() => {
      if (timeInterval) {
        clearInterval(timeInterval)
      }
      if (userChart) {
        userChart.dispose()
      }
      if (contentChart) {
        contentChart.dispose()
      }
      window.removeEventListener('resize', handleResize)
    })

    return {
      statsLoading,
      overviewStats,
      currentTime,
      userInfo,
      userChartPeriod,
      userChartRef,
      contentChartRef,
      totalContent,
      cultureCategories,
      navigateTo,
      changeUserChartPeriod,
      refreshData,
      formatDateTime
    }
  }
}
</script>

<style scoped>
.dashboard {
  padding: 20px;
}

/* 页面头部 */
.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
  padding-bottom: 16px;
  border-bottom: 2px solid #e4e7ed;
}

.header-info h2 {
  margin: 0 0 8px 0;
  font-size: 24px;
  font-weight: 600;
  color: #1a1a1a;
}

.header-info p {
  margin: 0;
  font-size: 14px;
  color: #666;
}

/* 统计卡片 */
.stats-cards {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(240px, 1fr));
  gap: 20px;
  margin-bottom: 24px;
}

.stat-card {
  background: white;
  padding: 24px;
  border-radius: 8px;
  border: 1px solid #e4e7ed;
  display: flex;
  align-items: center;
  gap: 16px;
  cursor: pointer;
  transition: all 0.3s ease;
  position: relative;
}

.stat-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  border-color: #8B0000;
}

.stat-icon {
  width: 56px;
  height: 56px;
  border-radius: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 24px;
  color: white;
  flex-shrink: 0;
}

.stat-icon.user-icon {
  background: #667eea;
}

.stat-icon.culture-icon {
  background: #8B0000;
}

.stat-icon.tutorial-icon {
  background: #00bcd4;
}

.stat-icon.news-icon {
  background: #43e97b;
}

.stat-info {
  flex: 1;
}

.stat-number {
  font-size: 32px;
  font-weight: 700;
  color: #1a1a1a;
  line-height: 1;
  margin-bottom: 6px;
}

.stat-label {
  font-size: 14px;
  color: #666;
}

.stat-trend {
  display: flex;
  align-items: center;
  gap: 4px;
  font-size: 14px;
  color: #67c23a;
  font-weight: 600;
}

/* 图表区域 */
.charts-row {
  margin-bottom: 24px;
}

.chart-card {
  background: white;
  padding: 24px;
  border-radius: 8px;
  border: 1px solid #e4e7ed;
  height: 400px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.card-header h3 {
  margin: 0;
  font-size: 16px;
  font-weight: 600;
  color: #1a1a1a;
}

.chart-legend {
  display: flex;
  gap: 16px;
}

.legend-item {
  display: flex;
  align-items: center;
  gap: 6px;
  font-size: 12px;
  color: #666;
}

.legend-dot {
  width: 8px;
  height: 8px;
  border-radius: 50%;
}

.legend-dot.culture {
  background: #8B0000;
}

.legend-dot.tutorial {
  background: #00bcd4;
}

.legend-dot.news {
  background: #43e97b;
}

.chart-container {
  height: 320px;
  width: 100%;
}

/* 底部区域 */
.bottom-row {
  margin-bottom: 24px;
}

/* 快捷操作 */
.quick-actions-card {
  background: white;
  padding: 24px;
  border-radius: 8px;
  border: 1px solid #e4e7ed;
}

.quick-actions {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
  gap: 12px;
}

.action-item {
  display: flex;
  align-items: center;
  padding: 16px;
  border-radius: 6px;
  border: 1px solid #e4e7ed;
  cursor: pointer;
  transition: all 0.3s ease;
  background: #fafafa;
}

.action-item:hover {
  background: white;
  border-color: #8B0000;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
}

.action-icon {
  width: 40px;
  height: 40px;
  border-radius: 6px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 18px;
  color: white;
  margin-right: 12px;
  flex-shrink: 0;
}

.action-icon.user-bg {
  background: #667eea;
}

.action-icon.culture-bg {
  background: #8B0000;
}

.action-icon.tutorial-bg {
  background: #00bcd4;
}

.action-icon.news-bg {
  background: #43e97b;
}

.action-icon.banner-bg {
  background: #f5576c;
}

.action-icon.setting-bg {
  background: #909399;
}

.action-content {
  flex: 1;
}

.action-content h4 {
  margin: 0 0 4px 0;
  font-size: 14px;
  font-weight: 600;
  color: #1a1a1a;
}

.action-content p {
  margin: 0;
  font-size: 12px;
  color: #909399;
}

.action-arrow {
  color: #c0c4cc;
  font-size: 14px;
  transition: all 0.3s ease;
}

.action-item:hover .action-arrow {
  color: #8B0000;
  transform: translateX(4px);
}

/* 系统信息 */
.system-info-card {
  background: white;
  padding: 24px;
  border-radius: 8px;
  border: 1px solid #e4e7ed;
}

.info-section {
  margin-bottom: 24px;
}

.info-section:last-of-type {
  margin-bottom: 16px;
}

.info-section h4 {
  margin: 0 0 12px 0;
  font-size: 14px;
  font-weight: 600;
  color: #1a1a1a;
  padding-bottom: 8px;
  border-bottom: 1px solid #f0f0f0;
}

.info-items {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.info-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 8px 0;
}

.info-label {
  font-size: 13px;
  color: #666;
}

.info-value {
  font-size: 13px;
  font-weight: 500;
  color: #1a1a1a;
}

.system-actions {
  display: flex;
  gap: 12px;
  padding-top: 16px;
  border-top: 1px solid #f0f0f0;
}

.system-actions .el-button {
  flex: 1;
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .stats-cards {
    grid-template-columns: repeat(2, 1fr);
  }
}

@media (max-width: 768px) {
  .dashboard {
    padding: 12px;
  }

  .page-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 12px;
  }

  .stats-cards {
    grid-template-columns: 1fr;
  }

  .chart-card {
    height: 320px;
  }

  .chart-container {
    height: 240px;
  }

  .quick-actions {
    grid-template-columns: 1fr;
  }
}
</style>
